﻿Imports System.IO.Ports
Imports System.ComponentModel

Public Class SRND_DAM
    ''' <summary>
    ''' 构造函数
    ''' </summary>
    ''' <param name="valPortName">串口名称</param>
    ''' <remarks></remarks>
    Public Sub New(valPortName As String)
        _PortName = valPortName
        SerialPort = New SerialPort(valPortName)
    End Sub

    '读温度的帧
    Private _FrameRdTmp As Byte() = New Byte() {&H1, &H3, &H0, &H0, &H0, &H4, &H44, &H9}
    '串口
    Public SerialPort As SerialPort

    <DescriptionAttribute("串口名称")>
    Public Property PortName As String
    <DescriptionAttribute("通道温度")>
    Public Property ChannelTemp As Double() = New Double(3) {}
    <DescriptionAttribute("接收缓存")>
    Public Property ReadBuffer As Byte() = New Byte(12) {}

    ''' <summary>
    ''' 启动设备
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub InitDevice()
        SerialPort.BaudRate = 9600
        SerialPort.DataBits = 8
        SerialPort.Parity = Parity.None
        SerialPort.StopBits = StopBits.One
        SerialPort.ReceivedBytesThreshold = 13
        Try
            SerialPort.Open()
            AddHandler SerialPort.DataReceived, AddressOf DataReadyHandler
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub

    ''' <summary>
    ''' 收到应答后的处理函数
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub DataReadyHandler(sender As Object,
                    e As SerialDataReceivedEventArgs)
        If SerialPort.BytesToRead >= SerialPort.ReceivedBytesThreshold Then
            SerialPort.Read(_ReadBuffer, 0, SerialPort.ReceivedBytesThreshold)
            ResolveReadBuffer()
        End If
    End Sub

    ''' <summary>
    ''' 解析接收缓存中的数据并更新到ChannelTemp中
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub ResolveReadBuffer()
        For i As Integer = 3 To 9 Step 2
            If ReadBuffer(i) > &H80 Then
                ChannelTemp((i - 3) / 2) = -0.1 * ((256 - ReadBuffer(i)) * 256 + ReadBuffer(i + 1))
            Else
                ChannelTemp((i - 3) / 2) = 0.1 * (ReadBuffer(i) * 256 + ReadBuffer(i + 1))
            End If
        Next
    End Sub

    ''' <summary>
    ''' 请求更新温度数据
    ''' </summary>
    ''' <remarks>更新到ChannelTemp中</remarks>
    Public Sub RequestTemp()
        SerialPort.Write(_FrameRdTmp, 0, _FrameRdTmp.Length)
    End Sub

End Class

